package com.scut.campus.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scut.campus.constant.MessageConstant;
import com.scut.campus.dto.UserLoginDTO;
import com.scut.campus.entity.User;
import com.scut.campus.exception.LoginFailedException;
import com.scut.campus.mapper.UserMapper;
import com.scut.campus.properties.WeChatProperties;
import com.scut.campus.service.UserService;
import com.scut.campus.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService{
    public static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        Map<String,String> map=new HashMap<>();
        map.put("appId",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code", userLoginDTO.getCode());
        map.put("grant_type","authorization_code");

        String json= HttpClientUtil.doGet(WX_LOGIN,map);
        JSONObject jsonObject= JSON.parseObject(json);
        String openid=jsonObject.getString("openid");

        if(openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }


        LambdaQueryWrapper<User>lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getOpenid,openid);
        User user=this.getOne(lambdaQueryWrapper);

        if(user==null){
            user=User.builder()
                    .openid(openid)
                    .build();
            userMapper.insert(user);
        }




        return user;
    }
}
